package com.jackeysun.common.text

import android.text.Spannable
import android.widget.TextView
import java.util.*
import java.util.regex.Pattern

/**
 *   Created by sunxunchao on 2021/12/31.
 */

/**
 * @param y y轴坐标
 * @return 第几行
 */
fun TextView.getLineByY(y: Int): Int {
    val layout = this.layout
    return layout.getLineForVertical(y)
}

/**
 * @param line 第几行
 * @return line行第一个字符排第几
 */
fun TextView.getStartByLine(line: Int): Int {
    val layout = this.layout
    return layout.getLineStart(line)
}

/**
 * @param line 第几行
 * @return line行最后一个字符排第几
 */
fun TextView.getEndByLine(line: Int): Int {
    val layout = this.layout
    return layout.getLineEnd(line)
}

/**
 * @param start 开始位置
 * @param end 结束位置
 * 截取字符串
 */
fun TextView.subChar(start: Int, end: Int): CharSequence? {
    val mSpan = if (this.text is Spannable) {
        this.text
    } else {
        null
    }
    return mSpan?.subSequence(start, end)
}

/**
 * @param x x轴坐标
 * @param y y轴坐标
 * @return 获取点击位置单词的开始位置
 */
fun TextView.getTouchWordStart(x: Int, y: Int): Int {
    val layout = this.layout
    val topVisibleLine = layout.getLineForVertical(y)
    val offset = layout.getOffsetForHorizontal(topVisibleLine, x.toFloat())
    val offsetX = layout.getPrimaryHorizontal(offset).toInt()
    return if (offsetX > x) {
        layout.getOffsetToLeftOf(offset)
    } else {
        offset
    }
}

/**
 * @param start 一个单词的开始位置
 * @param text 文本
 * @return 返回start附近匹配的单词中的第一个 没有则为null
 */
fun matchWord(start: Int, text: CharSequence): Word? {
    val words = getWordInfo(text)
    return try {
        words?.first { it.start <= start && it.end >= start }
    } catch (e: Exception) {
        null
    }
}

/**
 * @param text 文本
 * @return 返回text中的单词列表
 */
fun getWordInfo(text: CharSequence, regex: String = "[a-zA-Z]{2,}[\\']?[\\\\s]?"): List<Word>? {
    val words = splitWord(text,regex)
    if (words.isNullOrEmpty()) return null
    val result: MutableList<Word> = ArrayList()
    var startIndex = 0
    for (i in words.indices) {
        val word = words[i]
        val start: Int = text.toString().indexOf(word.toString(), startIndex)
        val end = start + word.length
        startIndex = end
        val wordInfo = Word(start, end)
        result.add(wordInfo)
    }
    return result
}

/**
 * 获取分割之后的所有单词
 *
 * @return
 */
fun splitWord(text: CharSequence?, regex: String): List<CharSequence>? {
    if (text.isNullOrEmpty()) {
        return null
    }
    val results: MutableList<CharSequence> = ArrayList()
    val pattern = Pattern.compile(regex)
    val matcher = pattern.matcher(text)
    while (matcher.find()) {
        matcher.group(0)?.let {
          val handleWord = it.specialWord()
            if (!handleWord.isNullOrEmpty()){
                results.add(handleWord)
            }
        }
    }
    return results

//    return text?.trim()?.split(Regex("\\s+"))
//        ?.map {
//            it.replace("[\";；：:.?!，,。？()（）【】\\[\\]{}@#\$%^&*~`~·|、\\\\]*".toRegex()) {
//                ""
//            }
//        }?.filter { !it.match() }?.map { it.specialWord().toString() }
////        ?.filter { !it.matches("\\d+".toRegex()) }
////        ?.filter { !it.matches("[a-zA-Z]".toRegex()) }
////        ?.filter { it.matches("[a-zA-Z]+[\']*[a-zA-Z]*".toRegex()) }
////        ?.filter { it.matches("[a-zA-Z]+[\']*[s]*".toRegex()) }
//
}

private fun CharSequence.match(): Boolean {
    return this.matches("\\d+".toRegex()) ||
            this.matches("[a-zA-Z]".toRegex()) ||
            this.matches("[\\u4e00-\\u9fa5]+".toRegex())
//            !this.matches("[a-zA-Z]+[\']{1}[\\s]{1}".toRegex())
}

/**
 * xxx'xxx的单词处理
 */
private fun CharSequence?.specialWord(): CharSequence? {
    return if (this.isNullOrEmpty()) return null
    else if (this.matches("[a-zA-Z]+[\']{1}[a-zA-Z]*".toRegex())) {
        val pattern = Pattern.compile("[a-zA-Z]+[']{1}[\\\\s]{1}")
        val matcher = pattern.matcher(this)
        if (matcher.matches()) {
            this.substring(0, this.length - 2)
        } else {
            null
        }
    } else {
        this
    }

//    while (matcher.find()) {
//       return try {
//            matcher.group(0)
//        }catch (e: Exception){
//            null
//        }
//    }
//    return this
}



